class MyTransformCode {
  constructor() {
    // 消息头包含 消息序列号 + 消息体长度
    this.headerLen = 4
    this.seriesNum = 0
    this.seriesLen = 2
  }

  encode(body, seriesNum) {
    // 将 body 转为 buffer
    body = Buffer.from(body)
    seriesNum = seriesNum || this.seriesNum

    // 消息头 buffer
    const headerBuff = Buffer.alloc(this.headerLen)
    // 将信息写入消息头 buffer 中
    headerBuff.writeInt16BE(seriesNum)
    headerBuff.writeInt16BE(body.length, this.seriesLen)

    if(seriesNum === undefined) {
      this.seriesNum++
    }
    
    // 返回
    return Buffer.concat([headerBuff, body])
  }

  decode(body) {
    return {
      seriesNum: body.readInt16BE(),
      bodyLen: body.readInt16BE(this.seriesLen), 
      body: body.slice(this.headerLen).toString()
    }
  }

  getPackageLen(buf) {
    if(buf.length < this.headerLen) {
      return 0
    }
    return this.headerLen + buf.readInt16BE(this.seriesLen)
  }
}

module.exports = MyTransformCode

